import {Worker, isMainThread, parentPort, workerData} from 'worker_threads';
import path from "path";

export function createTask(workerData) {
  return new Promise((resolve, reject) => {
    const worker = new Worker(path.join(__dirname, './worker-es6.js'), {workerData});
    console.log('threadId',worker.threadId);
    worker.on('message', (data) => {
      console.log('message', data);
      if (data.event == '任务创建成功') {
        resolve(data.value);
      }
    })
    worker.on('online', (data) => {
      console.log('线程online', data);
    })
    worker.on('exit', (data) => {
      console.log('线程exit', data);
    })
    worker.on('error', (data) => {
      console.log('线程error', data);
    })
  })
}

export function installPostMessage(target) {
  target.postMessage = (event, value) => {
    parentPort.postMessage({event, value});
  }
}

